#import "FlutterDouyinPlugin.h"
#import<DouyinOpenSDK/DouyinOpenSDKApplicationDelegate.h>
#import <DouyinOpenSDK/DouyinOpenSDKAuth.h>
#import <DouyinOpenSDK/DouyinOpenSDKShare.h>

static FlutterMethodChannel* channel;

@implementation FlutterDouyinPlugin

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    
    //    NSObject<FlutterTaskQueue>* taskQueue =
    //        [[registrar messenger] makeBackgroundTaskQueue];
    
    channel = [FlutterMethodChannel
               methodChannelWithName:@"flutter_douyin"
               binaryMessenger:[registrar messenger]];
    
    
    FlutterDouyinPlugin* instance = [[FlutterDouyinPlugin alloc] init];
    [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    if ([@"getPlatformVersion" isEqualToString:call.method]) {
        result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
    } if([@"setPlatformKey" isEqualToString:call.method]){//设置抖音平台key
        NSDictionary *arguments =  call.arguments;
        NSString * _key = [arguments objectForKey:@"iosKey"];
        [[DouyinOpenSDKApplicationDelegate sharedInstance] registerAppId:_key];
        result(@"success");
    }else if([@"douyinOpenSDKShareRequest" isEqualToString:call.method]){
        DouyinOpenSDKShareRequest *req = [[DouyinOpenSDKShareRequest alloc] init];
        
        
        NSDictionary* args =  [call arguments];
        NSString * shareType = args[@"shareType"];
        
        if(args[@"state"]!=nil ){
            req.state = args[@"state"];
        }else{
            result(@"缺少参数");
            return;
        }
        
        if([shareType isEqualToString:@"Capture"]){//打开视频
            req.shareAction = DouyinOpenSDKShareTypeCapture;
        }else if([shareType isEqualToString:@"mediaType"]){
            NSString * mediaType = args[@"mediaType"];
           
            NSArray* media =args[@"media"];
            req.localIdentifiers = media; // NSArray
            if([mediaType isEqualToString:@"Image"]){
                req.mediaType = DouyinOpenSDKShareMediaTypeImage;
            }else if([mediaType isEqualToString:@"Video"]){
                req.mediaType = DouyinOpenSDKShareMediaTypeVideo;
            }
            NSString * landedPageType = args[@"landedPageType"];
            if([landedPageType isEqualToString:@"Clip"]){
                req.landedPageType = DouyinOpenSDKLandedPageClip; // 剪辑页面
            }else if([landedPageType isEqualToString:@"Edit"]){
                req.landedPageType = DouyinOpenSDKLandedPageEdit; // 编辑页面
            }else if([landedPageType isEqualToString:@"Publish"]){
                req.landedPageType = DouyinOpenSDKLandedPagePublish; // 发布页面，现只支持单视频（需要抖音14.7版本以上）
            }
            
            
        }
        
        
        
        if(args[@"hashtag"]!=nil ){
            req.hashtag = args[@"hashtag"];
        }
        
        
        [req sendShareRequestWithCompleteBlock:^(DouyinOpenSDKShareResponse * _Nonnull respond) {
            NSMutableDictionary *dyAuthDic = [[NSMutableDictionary alloc] init];
            if (respond.isSucceed) {
                [dyAuthDic setValue:@"200" forKey:@"code"];
                [dyAuthDic setValue:@"分享成功" forKey:@"msg"];
                NSLog(@"分享成功返回：%@",dyAuthDic);
                [channel invokeMethod:@"ISO_DouyinOpenSDKShareRequest" arguments:dyAuthDic];
            } else{
                [dyAuthDic setValue:@(respond.errCode) forKey:@"code"];
                [dyAuthDic setValue:respond.errString forKey:@"errString"];
                NSLog(@"分享失败返回：%@",dyAuthDic);
                [channel invokeMethod:@"ISO_DouyinOpenSDKShareRequest" arguments:dyAuthDic];
            }
            
        }];
        result(@"success");
        
    }else if([@"douyinOpenSDKAuthRequest" isEqualToString:call.method]){
        
        NSDictionary* dictionary =  call.arguments;
        NSArray* permission =  dictionary[@"permissionMest"];
        NSArray* permissionOptional =  dictionary[@"permissionOptional"];
        
        NSMutableString *permissionmest = [[NSMutableString alloc]init];
        for(int i=0;i<permission.count;i++){
            NSString* _p =[permission[i] stringByAppendingString:@","];
            [permissionmest insertString:i+1==permission.count?permission[i]:_p atIndex:permissionmest.length];
        }
        
        NSLog(@"resp:%@",permission);
        
        
        DouyinOpenSDKAuthRequest *dyrequest = [[DouyinOpenSDKAuthRequest alloc] init];
        dyrequest.permissions = [NSOrderedSet orderedSetWithObject:permissionmest];
        if(permissionOptional!=nil){
            NSLog(@"Optional:%@",permissionOptional);
            for(int i=0;i<permissionOptional.count;i++){
                NSString * permissionName =permissionOptional[i];
                dyrequest.additionalPermissions = [NSOrderedSet orderedSetWithObjects:
                                                   @{ @"permission" : permissionName, @"defaultChecked" : @"1" },
                                                   nil];
            }
            
        }
        
        __weak typeof(self) ws = self;
        [dyrequest sendAuthRequestViewController:self completeBlock:^(DouyinOpenSDKAuthResponse * _Nonnull resp) {
            __strong typeof(ws) sf = ws;
            NSMutableDictionary *dyAuthDic = [[NSMutableDictionary alloc] init];
            if (resp.errCode == 0) {
                NSOrderedSet *orderSet = resp.grantedPermissions;
                NSArray* permissinosArray =  [orderSet array];
                NSMutableString *grantedPermissions = [[NSMutableString alloc]init];
                for(int i=0;i<permissinosArray.count;i++){
                    NSString* index =  permissinosArray[i];
                    NSString* _allpermission = [index stringByAppendingString:@","];
                    [grantedPermissions insertString:i+1==permissinosArray.count?index:_allpermission atIndex:grantedPermissions.length];
                }
                [dyAuthDic setValue:resp.code forKey:@"code"];
                [dyAuthDic setValue:grantedPermissions forKey:@"permissions"];
                NSLog(@"授权成功返回：%@",dyAuthDic);
                [channel invokeMethod:@"ISO_DouyinOpenSDKAuthRequest" arguments:dyAuthDic];
            } else{
                [dyAuthDic setValue:resp.code forKey:@"code"];
                [dyAuthDic setValue:resp.errString forKey:@"errString"];
                NSLog(@"授权失败返回：%@",dyAuthDic);
                [channel invokeMethod:@"ISO_DouyinOpenSDKAuthRequest" arguments:dyAuthDic];
            }
        }
        ];
        result(@"success");
    }else {
        result(FlutterMethodNotImplemented);
    }
}

@end
